package auctionhaus



import grails.test.mixin.*
import org.junit.*

/**
 * See the API for {@link grails.test.mixin.services.ServiceUnitTestMixin} for usage instructions
 */
@TestFor(BidCreateService)
@Mock([Bid,Customer,Listing])
class BidCreateServiceTests {

    Customer bidder
    Listing listing
    Customer seller
    
    @Before
    void setUp()
    {
        //seed database with test data
        seller = new Customer(email: "adambackstrom@gmail.com",password: "123456", enabled: true)
        assert seller.validate()
        seller.save(flush: true)

        bidder = new Customer(email: "kleczka@gmail.com",password: "7891011", enabled: true)
        assert bidder.validate()
        bidder.save(flush: true)

        //The listing has a starting price of 1.0 and and end date 1 day in the future
        listing = new Listing(name: "listing1",
                endDateTime: new Date() + 1,
                startingBidPrice: 10.0f,
                seller: seller)
        assert listing.validate()
        listing = listing.save(flush: true)

        println "Created Listing with id: " + listing.id
    }

    @Test
    void testAddBidOnListingValid()
    {
        assert Listing.count == 1

        Bid b = service.addBidOnListing(bidder, 10000, listing)

        assert !b.hasErrors()

        //validate bid is actually added
        assert Bid.count == 1
        Bid placedBid = Bid.findByListing(Listing.get(1))
        assert placedBid.bidder == Customer.findByEmail("kleczka@gmail.com")
        assert placedBid.amount == 10000
        assert listing.minimumBid == 10000.5
    }

    @Test
    void testAddBidOnListingCompleted()
    {
        assert Listing.count == 1
        listing.completed = true
        listing.save(flush: true)

        Bid b = service.addBidOnListing(bidder, 10000, listing)

        assert b.hasErrors()

        //validate bid is actually added
        assert Bid.count == 0
    }


    @Test
    void testAddBidOnListingInvalidBid()
    {
        assert Listing.count == 1

        Bid b = service.addBidOnListing(bidder, 1, listing)

        assert b.hasErrors()
        assert b.errors['amount'].code == 'validator.invalid'
    }
}
